import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/CartOrder.dart';

import 'MerchantPage.dart';

class Cart extends StatefulWidget {
  Cart({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _Cart createState() => _Cart();
}

class _Cart extends State<Cart> {
  num dabaofei=0;
  List CartGoods = [];//购物车集合
  // 构造函数
  _Cart(){
    _onLoading();
  }
  RefreshController _refreshController =
  RefreshController(initialRefresh: false);
  // 加载数据的函数
  void _onLoading() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String userId = prefs.getString("userId");
    // 发起请求
    var x = await HttpUtil().get("/waimai/mShopCat/getMShopcat?userId="+userId);
    if(x['code']==200){
      CartGoods.addAll(x['data']);
    }
    if(x['data'].length<1)
      _refreshController.loadNoData();
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    if(mounted)
      setState(() {

      });
  }

  Set xuanCart= Set(); // 勾选的商品
  int x=7;
  int gid=4;
  int count=0;
  bool isAll = false;
  num all = 0; // 所选商品总金额
  bool isShanchu=false;
  // 求总和
  // void _getAllMoney(){
  //   all=0;
  //   if(CartGoods.length>0){
  //     CartGoods.forEach((item)=>{
  //       if(item['isSelect']==true)
  //       {
  //         all= all + item['money']*item['scatNum']
  //       }
  //     });
  //     if(all>0) // 如果选择了商品，则显示删除按钮
  //       isShanchu=true;
  //     else
  //       isShanchu=false;
  //   }
  // }

  //按照店铺分类显示
  Widget _showMerchant(merchantList){
    List<Widget> x=[];
    for(int j=0;j<merchantList.length;j++){
      if(merchantList[j].length>0){
        x.add(
          Container(
              decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
              padding: EdgeInsets.all(2),
              margin: EdgeInsets.only(bottom: 10,left: 8,right: 8),
              child: _showGoods(merchantList[j])
          ),
        );
      }

    }
    return Container(
      width: ScreenUtil().setWidth(464),
      child: Column(children: x),
    );
  }

// 显示购物车中的商品
  Widget _showGoods(item){
    List<Widget> x=[];
    x.add(
      Row(
        children: [
          Checkbox(
              value: item[0]['isSelect'],
              onChanged: (val){// 点击勾选
                item[0]['isSelect']=val;
                for(int y=1;y<item.length;y++){
                  var original= item[y]['isSelect'];//原来的是与否
                  item[y]['isSelect']=val;
                  if(val==true){
                    isShanchu=true;
                    if(!original){
                      int dabao=((item[y]['mgoods']['gdabaofei']*100).floor())*item[y]['scatNum'];
                      int jiage=((item[y]['money']*100).floor())*item[y]['scatNum'];
                      all=(all+jiage+dabao);
                      dabaofei=(dabaofei+dabao);
                    }
                  }else{
                    isShanchu=false;
                    for(int a=0;a<CartGoods.length;a++){
                      for(int b=0;b<CartGoods[a].length;b++){
                        if(CartGoods[a][b]['isSelect']==true){
                          isShanchu=true;
                        }
                      }
                    }
                    int dabao=((item[y]['mgoods']['gdabaofei']*100).floor())*item[y]['scatNum'];
                    int jiage=((item[y]['money']*100).floor())*item[y]['scatNum'];
                    all=(all-jiage-dabao);
                    dabaofei=(dabaofei-dabao);
                  }
                }
                setState(() {

                });
              }
          ),
          Text(item[0]['mname'])
        ],
      )
    );
    for(int i=1;i<item.length;i++){
      x.add(
          Container(
            margin: EdgeInsets.only(bottom: 5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  width: ScreenUtil().setWidth(65),
                  child: Row(
                    children: [
                      Checkbox(
                          value: item[i]['isSelect'],
                          onChanged: (val){// 点击勾选
                            item[i]['isSelect']=val;
                            if(val==true){
                              isShanchu=true;
                              int sum=item.length-1;
                              for(int aa=1;aa<item.length;aa++){
                                if(item[aa]['isSelect']==false){
                                  break;
                                }else if(sum==aa){
                                  item[0]['isSelect']=true;
                                }
                              }
                              int dabao=((item[i]['mgoods']['gdabaofei']*100).floor())*item[i]['scatNum'];
                              int jiage=((item[i]['money']*100).floor())*item[i]['scatNum'];
                              all=(all+jiage+dabao);
                              dabaofei=(dabaofei+dabao);
                            }else if(val==false){
                              isShanchu=false;
                              for(int a=0;a<CartGoods.length;a++){
                                for(int b=0;b<CartGoods[a].length;b++){
                                  if(CartGoods[a][b]['isSelect']==true){
                                    isShanchu=true;
                                  }
                                }
                              }
                              item[0]['isSelect']=false;
                              int dabao=((item[i]['mgoods']['gdabaofei']*100).floor())*item[i]['scatNum'];
                              int jiage=((item[i]['money']*100).floor())*item[i]['scatNum'];
                              all=(all-jiage-dabao);
                              dabaofei=(dabaofei-dabao);
                            }
                            setState(() {

                            });
                          }
                      ),
                    ],
                  ),
                ),
                Expanded(
                    child: InkWell(
                      child: Row(
                        children: [
                        CachedNetworkImage(imageUrl: Config.getInstance().getHost()+item[i]['mgoods']['gimages'],width: 70,height: 70,),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              padding: EdgeInsets.only(top: 4),
                              margin: EdgeInsets.only(left: 5),
                              width: ScreenUtil().setWidth(260),
                              height: ScreenUtil().setHeight(30),
                              child: Row(
                                children: [
                                  Expanded(child: Text(item[i]['mgoods']['gname'],style: TextStyle(fontSize: 14)),),
                                  Row(
                                    children: [
                                      Text("￥",style: TextStyle(fontSize: 12,color: Colors.red)),
                                      Text("${item[i]['money']}",style: TextStyle(fontSize: 15,color: Colors.red)),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(height: 8,),
                            Container(
                              width: ScreenUtil().setWidth(260),
                              height: ScreenUtil().setHeight(26),
                              margin: EdgeInsets.only(left: 5),
                              child: Row(
                                children: [
                                  Expanded(child: Text(item[i]['guiges']==null ? "" : getGuigeString(item[i]['mgoods']['guige'], item[i]['guigeparams']),maxLines: 2,overflow: TextOverflow.ellipsis,style: TextStyle(fontSize: 12,color: Colors.grey),))
                                ],
                              ),
                            ),
                            SizedBox(height: 8,),
                            Container(
                              margin: EdgeInsets.only(left: 5),
                              child: Text("x${item[i]['scatNum']}",style: TextStyle(color: Colors.grey)),
                            ),
                          ],
                        )
                      ],
                    ),onTap: () async {
                        print(item[i]['mgoods']['id']);
                        print(item[i]['mgoods']['gtypeId']);
                        var x=await HttpUtil().get("/waimai/mGoodsType/getMtypeId?gTypeId="+item[i]['mgoods']['gtypeId']);
                        if(x['code']==200){
                          print(x['data']);
                          MyRoute.push(MerchantPage(merchantId: item[i]['mgoods']['mid'],merchantTypeId: x['data'],));
                        }
                    },
                    )

                )
              ],
            ) ,
          )
      );
    }
    return Column(
      children: x,
    );
  }

  //解析购物车商品的规格
  String getGuigeString(val,params){
    List list=json.decode(val);
    List param=json.decode(params);
    int size=param.length;
    String str='';
    for(int i=0;i<size;i++){
      String value=list[i]['value'];
      var array=value.split('-');
      str+=list[i]['name']+":"+array[param[i]]+"  ";
    }
    return str;
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return Scaffold(
      appBar: AppBar(
        title: Text("购物车"),
        actions: [
         isShanchu ?
         IconButton(
             icon: Icon(Icons.remove_shopping_cart),
             onPressed: () async {
               showDialog<Null>(
                 context: context,
                 barrierDismissible: false,
                 builder: (BuildContext context) {
                   return new AlertDialog(
                     title: new Text('删除该购物车'),
                     content: Text('确定删除?'),
                     actions: <Widget>[
                       new FlatButton(
                         child: new Text('取消'),
                         onPressed: (){
                           Navigator.of(context).pop();
                         },
                       ),
                       new FlatButton(
                         child: new Text('确定'),
                         onPressed: () async{
                           var delList=[];
                           var s = "catid=";
                           for(int i=0;i<CartGoods.length;i++){
                             for(int y=1;y<CartGoods[i].length;y++){
                               if( CartGoods[i][y]['isSelect']==true){
                                 delList.add(CartGoods[i][y]['id']);
                                 s=s+CartGoods[i][y]['id']+"&catid=";
                               }
                             }
                           }
                           // 发起请求删除购物车
                           var x= await HttpUtil().get("waimai/mShopCat/deleteCart?"+s);
                           if(x['code']==200){// 如果删除成功
                             // 删除当前数组中的数据
                             for(int i=0;i<CartGoods.length;i++){
                               List merchantList=CartGoods[i];
                               for(int y=0;y<merchantList.length;y++){
                                 if(merchantList[y]['isSelect']==true){
                                   if(y>=1){
                                     int dabao=((merchantList[y]['mgoods']['gdabaofei']*100).floor())*merchantList[y]['scatNum'];
                                     int jiage=((merchantList[y]['money']*100).floor())*merchantList[y]['scatNum'];
                                     all=(all-jiage-dabao);
                                     dabaofei=(dabaofei-dabao);
                                   }
                                   merchantList.removeAt(y);
                                   y--;
                                 }
                               }
                               if(CartGoods[i].length==0){
                                 CartGoods.removeAt(i);
                                 i--;
                               }
                             }
                             setState(() {

                             });
                             Fluttertoast.showToast(
                                 msg: "删除成功",
                                 toastLength: Toast.LENGTH_SHORT,
                                 gravity: ToastGravity.BOTTOM,
                                 timeInSecForIosWeb: 1,
                                 backgroundColor: Colors.black45,
                                 textColor: Colors.white,
                                 fontSize: 16.0
                             );
                             Navigator.of(context).pop();
                           }
                         }
                       ),
                     ],
                   );
                 },
               ).then((val) {
                 print(val);
               });

             }) : Text("")
        ],
      ),
      body:Container(
        decoration: new BoxDecoration(color: Colors.black12),
        child:new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children:[
            CartGoods.length==0
                ?
            new Expanded(
              child: Container(
                child: Text("购物车没有商品!",
                    textAlign: TextAlign.center),
                width: double.infinity,
              )
            )
                :
            Expanded(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SingleChildScrollView(
                      child: _showMerchant(CartGoods),
                    )
                  ],
                )
            ),
            Container(    //底部结算部分
              decoration:  new BoxDecoration(
                //背景
                color: Colors.white,
                //设置四周边框
                border: new Border.all(width: 0, color: Colors.white),
              ),
              child: Row(
                children: <Widget>[
                  // new Checkbox(
                  //       value: isAll,
                  //       activeColor: Color.fromARGB(255, 255, 67, 78),
                  //       onChanged: (bool) {
                  //         isAll=bool;
                  //         for(int i=0;i<CartGoods.length;i++){
                  //           for(int j=0;j<CartGoods[i].length;j++){
                  //             CartGoods[i][j]['isSelect']=bool;
                  //             if(j>=1){
                  //               if(bool==true){
                  //                 int dabao=((CartGoods[i][j]['mgoods']['gdabaofei']*100).floor())*CartGoods[i][j]['scatNum'];
                  //                 int jiage=((CartGoods[i][j]['money']*100).floor())*CartGoods[i][j]['scatNum'];
                  //                 all=((all*100).floor()+jiage+dabao)/100;
                  //                 dabaofei=((dabaofei*100).floor()+dabao)/100;
                  //               }else{
                  //                 int dabao=((CartGoods[i][j]['mgoods']['gdabaofei']*100).floor())*CartGoods[i][j]['scatNum'];
                  //                 int jiage=((CartGoods[i][j]['money']*100).floor())*CartGoods[i][j]['scatNum'];
                  //                 all=((all*100).floor()-jiage-dabao)/100;
                  //                 dabaofei=((dabaofei*100).floor()-dabao)/100;
                  //               }
                  //             }
                  //           }
                  //         }
                  //         setState(() {});
                  //       }
                  //     ),
                  // Text("全选"),
                  Expanded(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        Text(
                          "打包费："+(dabaofei/100).toString(),
                          style: TextStyle(color: Colors.grey, fontSize: 14),
                        ),
                        Text(
                          "合计:",
                          style: TextStyle(color: Colors.black, fontSize: 16),
                        ),
                        Text(
                          "￥",
                          style: TextStyle(color: Colors.red, fontSize: 16),
                        ),
                        Text(
                          "${all/100}",
                          style: TextStyle(
                            color: Colors.red,
                            fontSize: 18,
                          ),
                        ),
                        GestureDetector(child:Container(
                          alignment: Alignment.center,
                          child: new Text(
                            "结算",
                            style: TextStyle(color: Colors.white,fontSize: 20),
                          ),
                          width: ScreenUtil().setWidth(140),
                          height: 50,
                          color: Colors.red,
                        ) ,
                          onTap: () async {
                          List cartList=[];     //选中的商品购物车列表
                          String merchantName='a';//店铺名字
                          String merchantId='a'; //店铺id
                          int cartsize=0;       //选中的商品的数量
                            int sum=0;
                            for(int a=0;a<CartGoods.length;a++){
                              if(sum>=2){
                                break;
                              }
                              if(CartGoods[a][0]['isSelect']==true ){
                                sum++;
                                continue;
                              }
                              for(int b=1;b<CartGoods[a].length;b++){
                                if(CartGoods[a][b]['isSelect']==true){
                                  sum++;
                                  break;
                                }
                              }
                            }
                            if(sum>=2){
                              Fluttertoast.showToast(
                                  msg: "不能同时结算两个商家的订单",
                                  toastLength: Toast.LENGTH_SHORT,
                                  gravity: ToastGravity.BOTTOM,
                                  timeInSecForIosWeb: 1,
                                  backgroundColor: Colors.black45,
                                  textColor: Colors.white,
                                  fontSize: 16.0
                              );
                              return;
                            }
                            for(int a=0;a<CartGoods.length;a++){
                              List mList=CartGoods[a];
                              for(int c=1;c<mList.length;c++){
                                print(mList[c]['isSelect']);
                                if(mList[c]['isSelect']==true){
                                  merchantName=mList[0]['mname'];
                                  merchantId=mList[0]['id'];
                                  cartList.add(mList[c]);
                                  cartsize=cartsize+mList[c]['scatNum'];
                                }
                              }
                            }
                            if(cartList.length<=0){
                              Fluttertoast.showToast(
                                  msg: "请选择商品",
                                  toastLength: Toast.LENGTH_SHORT,
                                  gravity: ToastGravity.BOTTOM,
                                  timeInSecForIosWeb: 1,
                                  backgroundColor: Colors.black45,
                                  textColor: Colors.white,
                                  fontSize: 16.0
                              );
                              return;
                            }
                            var x = await MyRoute.push(CartOrder(orRemark: "",cartList: cartList,merchantName: merchantName,dabaofei: dabaofei/100,zongjia: (all/100).toString(),cartsize: cartsize,merchantId: merchantId,));
                            print(x);
                          },
                        )
                      ],
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      )

    );
  }

}